# -*- coding: UTF-8 -*-

class request(object):

    def __init__(self, transport_core):
        self.core = transport_core


    def sGet(self, mSession = None, **other):
        try:
            if mSession is None:
                mSession = self.core.loader.instance('requests', 'Session')
            response = mSession.get(**other)
            return self.core.lib.outputobj(response.ok, '请求成功' if response.ok else '请求失败', response)
        except Exception, e:
            return self.core.lib.outputobj(False, '请求异常：%s' % str(e), e)


    def sPost(self, mSession = None, jsonData = True, **other):
        try:
            if mSession is None:
                mSession = self.core.loader.instance('requests', 'Session')
            if other.get('data', {}) and jsonData:
                other['data'] = self.core.loader.module('json').dumps(other['data'])
            response = mSession.post(**other)
            return self.core.lib.outputobj(response.ok, '请求成功' if response.ok else '请求失败', response)
        except Exception, e:
            return self.core.lib.outputobj(False, '请求异常：%s' % str(e), e)


    def convertUtf8Text(self, response):
        if hasattr(response, 'text'):
            try:
                response.encoding = 'utf-8'
                return self.core.lib.outputobj(True, '成功获取文本内容', response.text)
            except Exception, e:
                return self.core.lib.outputobj(False, '解析异常：%s' % str(e), response.text)
        else:
            return self.lib.outputobj(False, '未获取到请求文本', '')

    def decodeJsonContent(self, response, **other):
        if hasattr(response, 'content'):
            try:
                return self.core.lib.outputobj(True, '成功解析二进制内容', self.core.loader.module('json').loads(response.content.decode('utf-8', **other)))
            except Exception, e:
                return self.core.lib.outputobj(False, '解析异常：%s' % str(e), response.content)
        else:
            return self.core.lib.outputobj(False, '未获取到二进制响应内容')
